﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Fireball.Extensions
{
    public static class StreamExtensions
    {
        /// <summary>
        /// Returns all bytes from a stream
        /// </summary>
        /// <param name="strm">The stream to read from</param>
        /// <returns>All the bytes from the current stream position</returns>
        public static byte[] GetAllBytes(this Stream strm)
        {
            if (strm == Stream.Null || strm.Length == 0)
                return null;

            List<byte> bts = new List<byte>();


            while (true)
            {
                var bts_t = new byte[1024];

                var c = strm.Read(bts_t, 0, 1024);

                if (c == 0) break;

                if (c < 1024)
                {
                    for (int i = 0; i < c; i++)
                        bts.Add(bts_t[i]);
                }
                else
                {
                    bts.AddRange(bts_t);
                }
            }
            return bts.ToArray();
        }

        /// <summary>
        /// Return the md5 Hash for the specified stream
        /// </summary>
        /// <param name="strm">The stream where calculate the md5 hash</param>
        /// <returns>The md5 hash string</returns>
        public static string GetMd5(this Stream strm)
        {
            if (strm == Stream.Null || strm.Length == 0)
                return null;

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            UTF8Encoding enc = new UTF8Encoding();
            byte[] hash = md5.ComputeHash(strm);
            StringBuilder buff = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)
            {
                buff.Append(String.Format("{0:x2}", hash[i]));
            }

            return buff.ToString();
        }

    }
}
